<?php
namespace app\lnadmin\controller;

use app\common\controller\AdminBase;
use think\facade\View;
use think\facade\Db;

use app\common\model\AuthRule;
use app\common\model\AuthGroup;

class Auth extends AdminBase
{
    protected function _initialize()
    {
        parent::_initialize();
    }
    /**
     * 部门管理
     * @return mixed
     */
    public function group()
    {
        return $this->fetch('group');
    }

    /**
     * 部门管理JSON
     * @param string $limit 分页
     * @throws \think\db\exception\DbException
     */
    public function group_json($limit='15')
    {
        $list =  AuthGroup::paginate($limit);
        $this->result($list);
    }

    /**
     * 添加新的部门
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addGroup()
    {
        if ($this->request->isPost()) {
            $result = AuthGroup::create($this->request->param());
            if ($result == true) {
                insert_admin_log('添加了用户组');
                $this->success('添加成功', url('lnadmin/auth/group'));
            } else {
                $this->error($this->errorMsg);
            }
        }
        $authRule = collection(AuthRule::where(['status' => 1])->order('sort_order asc')->select())->toArray();
        foreach ($authRule as $k => $v) {
            //$authRule[$k]['open'] = true;
        }
        
        return View::fetch('saveGroup', ['authRule' => list_to_tree($authRule)]);
    }

    /**
     * 修改部门
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editGroup()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $verify = input('_verify', true);
            //验证规则
            if($verify!='0'){
                try{
                    $this->validate($param, 'authGroup');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            //更新数据
            $resule = AuthGroup::update($param);
            if ( $resule == true) {
                insert_admin_log('修改了用户组');
                $this->success('修改成功', url('lnadmin/auth/group'));
            } else {
                $this->error($this->errorMsg);
            }
        }
        $data     = AuthGroup::where('id', input('id'))->find();
        $authRule = collection(AuthRule::where(['status' => 1])->order('sort_order asc')->select())->toArray();
        foreach ($authRule as $k => $v) {
            // $authRule[$k]['open'] = true;
            $authRule[$k]['checked'] = in_array($v['id'], explode(',', $data['rules']));
        }
        return $this->fetch('saveGroup', ['data' => $data, 'authRule' => list_to_tree($authRule)]);
    }

    /**
     * 删除部门
     */
    public function delGroup()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            AuthGroup::destroy($param['id']);
            insert_admin_log('删除了用户组');
            $this->success('删除成功');
        }
    }

    /**
     * 角色管理
     * @return mixed
     */
    public function rule()
    {
        return $this->fetch('rule');
    }

    /**
     * 角色管理JSON
     * @return false|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function rule_json()
    {
        $authRule = collection(AuthRule::where(['status' => 1])->order('sort_order asc')->select())->toArray();
        $count = collection(AuthRule::where(['status' => 1])->order('sort_order asc')->select())->count();
        foreach ($authRule as $k => $v) {
            $data[$k] = array(
                  'authorityId' =>$v['id'],
                  "authorityName" => $v['name'],
                  "authority" =>$v['url'],
                  "menuUrl" =>$v['url'],
                  "parentId" =>$v['pid'],
                  "isMenu" =>$v['type']=='nav'?0:1,
                  "orderNumber" =>$v['sort_order'],
                  "menuIcon" =>$v['icon'],
                  "status" =>$v['status'],
                  "createTime" =>'',
                  "updateTime" =>'',
                  "open"=> $v['status']?true:false
                );
        }
        $arrayName = array('code' =>0,'msg' =>'加载成功','count' =>$count,'data' =>$data);
        return json_encode($arrayName);
    }

    /**
     * 添加新的角色
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addRule()
    {
        if ($this->request->isPost()) {
            $result = AuthRule::create($this->request->param());
            if ($result == true) {
                insert_admin_log('添加了权限规则');
                $this->success('添加成功', url('lnadmin/auth/rule'));
            } else {
                $this->error($this->errorMsg);
            }
        }
        $authRule = AuthRule::where(['status' => 1])->order('sort_order asc')->select();
        return $this->fetch('saveRule', ['authRule' => list_to_level($authRule)]);
    }

    /**
     * 修改角色
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editRule()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = AuthRule::update($param,['id'=>$param['id']]);
            if ($result == true) {
                insert_admin_log('修改了权限规则');
                $this->success('修改成功', url('lnadmin/auth/rule'));
            } else {
                $this->error($this->errorMsg);
            }
        }
        $authRule = AuthRule::where(['status' => 1])->order('sort_order asc')->select();
        return $this->fetch('saveRule', ['data' => AuthRule::where('id', input('id'))->find(),'authRule' => list_to_level($authRule)]);
    }

    /**
     * 删除角色
     */
    public function delRule()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            AuthRule::where('pid', input('id'))->count() && $this->error('请先删除子节点');
            AuthRule::destroy($param['id']);
            insert_admin_log('删除了权限规则');
            $this->success('删除成功');
        }
    }
    
}
